#include "StdAfx.h"
#include "Key.h"
#include "Level.h"
#include "CubePhysX.h"
#include "NxActor.h"
#include "Character.h"
#include "NxShape.h"
#include "Sphere.h"
#include "DX10ObjMesh.h"
#include "ObjReader.h"
#include "D3DApp.h"

Key::Key(Level* level,PhysX* physics,int id,D3DXVECTOR3 position, bool rotate,D3DApp *app):
	LevelElement(),		
	m_ID(id),
	m_Position(position),
	m_pDrawMesh(0),
	m_Rotate(rotate),
	m_yRot(0),
	m_pPhysX(physics),
	m_app(app)
{
	m_pLevel = level;
}

Key::~Key(void)
{
	//delete m_pDrawMesh;
	delete m_pTrigger;
}


void Key::Tick(const InputState& inputState)
{		
	if(m_Rotate)
	{
		m_pDrawMesh->ResetWorldMatrix();
		D3DXVECTOR3 rotator(0.0f,m_yRot,0.0f);
		m_pDrawMesh->Rotate(rotator);
		m_pDrawMesh->Translate(m_Position);
		//Deze waarde moet nog aangepast worden
		m_yRot += 0.01f; //57,29577951;
	}
	m_pDrawMesh->Tick(inputState);
	m_pTrigger->Tick(inputState);
}
void Key::Draw(const RenderContext* context, ID3D10ShaderResourceView* shadowdepthmap) {
	if ( m_pDrawMesh )
		m_pDrawMesh->Draw(context, shadowdepthmap);
}

void Key::Initialize(ContentManager* manager)
{
	BuildDrawMesh();

	//m_pDrawMesh->SetParent(m_pLevel);
	m_pDrawMesh->Initialize(manager);
	m_pLevel->AddChild(m_pDrawMesh);

	m_pTrigger = new CubePhysX(m_pLevel, 1.5f, 1.5f, 1.5f,D3DXCOLOR(1,1,1,1),CubePhysX::GHOST);
	m_pTrigger->Translate(m_Position);

	m_pTrigger->GetActor()->userData = this;

}

void Key::OnTriggerEnter(Character* player)
{
	player->AddToInventory(this);
	m_pLevel->RemoveChild(m_pDrawMesh);
	m_pLevel->RemoveChild(this);
	DisableTrigger();
	
}

void Key::OnTriggerExit(Character* player)
{
	
}

void Key::DisableTrigger()
{
	m_pTrigger->GetActor()->raiseActorFlag(NX_AF_DISABLE_COLLISION);
}

void Key::BuildDrawMesh()
{
	IniFile* config = new IniFile();
	config->SetValue(_T("Export"),_T("baseDir"),_T("."));
	config->SetValue(_T("Export"),_T("meshDir"),_T(""));
	config->SetValue(_T("Export"),_T("textureDir"),_T(""));
	config->SetValue(_T("Export"),_T("skeletonDir"),_T(""));

	ObjReader reader(config,_T("./Models/Key/key.obj"));
	if ( reader.Read() )
	{
		MeshList* list = new MeshList();
		reader.CopyIntoMeshList(list);
		vector<ObjMesh*>::const_iterator it;
		for (it=list->begin(); it!= list->end(); it++)
		{
			ObjMesh* mesh = *it;
			// standaard shader meegeven
			DX10ObjMesh* dx10Mesh = m_app->Compile(mesh,_T("NormalMap.fx"), _T("checkertech"));
			if ( dx10Mesh != 0 )
			{
				m_pDrawMesh = dx10Mesh;
			}
		}
	}
}